<?php

namespace app\admin\model;

use EasyWeChat\Factory;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;
    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'createtime_text',
        'images_url',
        'status_text',
        'is_explosive_text',
        'is_overbalance_text',
        'is_recommend_text'
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }

    public function getIsExplosiveList()
    {
        return ['1' => __('Is_explosive 1'), '2' => __('Is_explosive 2')];
    }

    public function getIsOverbalanceList()
    {
        return ['1' => __('Is_overbalance 1'), '2' => __('Is_overbalance 2')];
    }

    public function getIsRecommendList()
    {
        return ['1' => __('Is_recommend 1'), '2' => __('Is_recommend 2')];
    }
    // 获取器直接转换url
    public function getImagesUrlAttr($value,$data)
    {
        $url = [];
        if($data['image']){
            $data['image'] = explode(',',$data['image']);
            if(count($data['image']) > 0){
                foreach ($data['image'] as $v){
                    // 解析图片地址
                    $parsedUrl = parse_url($v);
                    // 判断图片地址是否包含域名
                    if (isset($parsedUrl['host'])) {
                        array_push($url,$v);
                    } else {
                        array_push($url,complete_url($v));
                    }
                }
            }
        }
        return $url;
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getIsExplosiveTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_explosive']) ? $data['is_explosive'] : '');
        $list = $this->getIsExplosiveList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getIsOverbalanceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_overbalance']) ? $data['is_overbalance'] : '');
        $list = $this->getIsOverbalanceList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getIsRecommendTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_recommend']) ? $data['is_recommend'] : '');
        $list = $this->getIsRecommendList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function collect()
    {
        return $this->hasMany('Usercollect','good_id','id');
    }
    public function cart()
    {
        return $this->belongsTo('Cart','id','good_id');
    }
    public function order()
    {
        return $this->belongsTo('Order','id','good_id');
    }

    /**
     * 添加
     * @return void
     */
    public function add($goods,$user_id,$transaction_id)
    {
        $earnest_money = isset($goods->earnest_money) ? $goods->earnest_money : 0;
        $service = $goods->price * $goods->num * $goods->seller_commission;
        $is_explosive = 2;
        if(isset($goods->is_explosive) && $goods->is_explosive != ''){
            $is_explosive = 1;
        }
        $is_overbalance = 2;
        if(isset($goods->is_overbalance) && $goods->is_overbalance != ''){
            $is_overbalance = 1;
        }
        $is_recommend = 2;
        if(isset($goods->is_recommend) && $goods->is_recommend != ''){
            $is_recommend = 1;
        }
        $good_id = \db('goods')->insertGetId([
            'user_id' => $user_id,
            'transaction_id' => $transaction_id,//微信订单号
            'title' => $goods->title,
            'image' => $goods->image,
            'images' => $goods->images,
            'price' => $goods->price,
            'describe' => $goods->describe,
            'selltime' => $goods->selltime,
            'real_name' => $goods->real_name,
            'phone' => $goods->phone,
            'seller_commission' => $goods->seller_commission,
            'is_seller' => $goods->is_seller,
            'manner_packing' => $goods->manner_packing,
            'breed' => $goods->breed,
            'delivery_method' => $goods->delivery_method,
            'num' => $goods->num,
            'caretory' => $goods->caretory,
            'place_origin' => $goods->place_origin,
            'exposure_fee' => isset($goods->exposure_fee) ? $goods->exposure_fee : null,
            'referral_fee' => isset($goods->referral_fee) ? $goods->referral_fee : null,
            'premium_fee' => isset($goods->premium_fee) ? $goods->premium_fee : null,
            'earnest_money' => $earnest_money,
            'service' => $service,
            'is_explosive' => $is_explosive,
            'is_overbalance' => $is_overbalance,
            'is_recommend' => $is_recommend,
            'status' => 1,
            'createtime' => time(),
            'updatetime' => time()
        ]);
        if($good_id){
            if(isset($goods->is_explosive) && $goods->is_explosive != ''){
                db('explosive_goods')->insert([
                    'goods_id' => $good_id,
                    'user_id' => $user_id,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
            if(isset($goods->is_overbalance) && $goods->is_overbalance != ''){
                db('overbalance_goods')->insert([
                    'goods_id' => $good_id,
                    'user_id' => $user_id,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
            if(isset($goods->is_recommend) && $goods->is_recommend != ''){
                db('recommend_goods')->insert([
                    'goods_id' => $good_id,
                    'user_id' => $user_id,
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
            }
            return true;
        }
        return false;
    }
    /**
     * 到期未交易退还押金
     */
    public function earnestReturn($goods)
    {
        $transaction_id = $goods['transaction_id'];
        $totalFee = $goods['earnest_money'] + $goods['exposure_fee']+ $goods['referral_fee'] + $goods['premium_fee'];
        $refundFee = $goods['earnest_money'];
        $config = $this->config();
        $app = Factory::payment($config);
        $refundNumber = 'tk'.time().rand(1000,9999);
        // 参数分别为：微信订单号、商户退款单号、订单金额、退款金额、其他参数
        $result = $app->refund->byTransactionId($transaction_id, $refundNumber, intval($totalFee * 100), intval($refundFee * 100), [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退还保证金',
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] != 'FAIL'){
            self::where('id',$goods['id'])->update([
                'status'=>3
            ]);
        }
    }
    /**
     * 配置
     * @return string[]
     */
    public function config()
    {
        //获取插件
        $config = get_addon_config('epay');
        $config = [
            // 必要配置
            'app_id' => $config['wechat']['miniapp_id'],
            'mch_id' => $config['wechat']['mch_id'],
            'key' => $config['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => ROOT_PATH.'addons/epay/certs/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => ROOT_PATH.'addons/epay/certs/apiclient_key.pem',      // XXX: 绝对路径！！！！
            'notify_url' => '',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return $config;
    }
}
